package com.uduemc.biso.node.module.common.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.common.entities.FormData;
import com.uduemc.biso.node.core.entities.SForm;
import com.uduemc.biso.node.module.common.service.CFormService;
import com.uduemc.biso.node.module.service.SFormService;

/**
 * 公共的站点基本数据获取服务控制器
 * 
 * @author guanyi
 *
 */
@RestController
@RequestMapping("/common/form")
public class CFormController {

	@Autowired
	private CFormService cFormServiceImpl;

	@Autowired
	private SFormService sFormServiceImpl;

	/**
	 * 通过 formId、hostId、siteId 获取 FormData 数据
	 * 
	 * @param formId
	 * @param hostId
	 * @param siteId
	 * @return
	 */
	@GetMapping("find-one-by-form-host-site-id/{formId:\\d+}/{hostId:\\d+}/{siteId:\\d+}")
	public RestResult findOneByFormHostSiteId(@PathVariable("formId") long formId, @PathVariable("hostId") long hostId,
			@PathVariable("siteId") long siteId) {
		FormData formData = cFormServiceImpl.findOneByFormHostSiteId(formId, hostId, siteId);
		if (formData == null) {
			return RestResult.noData();
		}
		return RestResult.ok(formData, FormData.class.toString());
	}

	/**
	 * 通过 hostId、siteId 获取 FormData 数据列表
	 * 
	 * @param hostId
	 * @param siteId
	 * @return
	 */
	@GetMapping("find-infos-by-host-site-id/{hostId:\\d+}/{siteId:\\d+}")
	public RestResult findInfosByHostSiteId(@PathVariable("hostId") long hostId, @PathVariable("siteId") long siteId) {
		List<FormData> listFormData = cFormServiceImpl.findInfosByHostSiteId(hostId, siteId);
		if (CollectionUtils.isEmpty(listFormData)) {
			return RestResult.noData();
		}
		return RestResult.ok(listFormData, FormData.class.toString(), true);
	}

	/**
	 * 通过 formId、hostId、siteId 删除整个 SForm 数据，包含前台表单提交的数据！
	 * 
	 * @param formId
	 * @param hostId
	 * @param siteId
	 * @return
	 */
	@GetMapping("delete-form-by-form-host-site-id/{formId:\\d+}/{hostId:\\d+}/{siteId:\\d+}")
	public RestResult deleteFormByFormHostSiteId(@PathVariable("formId") long formId,
			@PathVariable("hostId") long hostId, @PathVariable("siteId") long siteId) {
		SForm sForm = sFormServiceImpl.findByHostSiteIdAndId(formId, hostId, siteId);
		if (sForm == null) {
			return RestResult.error();
		}
		// 删除
		cFormServiceImpl.deleteForm(sForm);
		return RestResult.ok(sForm, SForm.class.toString());
	}
}
